package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类，定时处理订单状态
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理未支付的超时订单，每分钟触发一次
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOuder(){
        log.info("定时处理超时订单：{}", LocalDateTime.now());
        //先查看超时订单 select * from orders where status = 待付款 15min <当前时间-and order_time?
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> list = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, time);
        if(list!=null&&list.size()>0){
            for(Orders order:list){
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("订单超时，自动取消");
                orderMapper.update(order);
            }
        }

    }

    /**
     *定时处理一直处于派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ? ")
    public void processDeliveryOrder(){
        log.info("定时处理一直在派送中的订单：{}", LocalDateTime.now());
        //12点下班，1点执行，清理的是上一个工作日的，所以用当前时间-60min
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        List<Orders> list = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, time);
        if(list!=null&&list.size()>0){
            for(Orders order:list){
                order.setStatus(Orders.COMPLETED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("订单超时，自动取消");
                orderMapper.update(order);
            }
        }
    }
}
